<?php

class MTaskApplyNum extends MY_Model
{

    protected $table = 'task_apply_num';

    function __construct()
    {
        parent::__construct();
    }

    public function updateCepingCount($task_id, $operator_id)
    {
        $this->db->select('id,ceping_type,order_no');
        $this->db->from('task_operate');
        $this->db->where(array('task_id' => $task_id, 'operator_id' => $operator_id, 'status <>' => 4));
//        $this->db->group_by('order_no');
        $list = $this->db->get()->result();
        $sales = 0;
        $cepings = 0;
        $cepings_arr = array();
        foreach ($list as $v) {
            $cepings_arr[$v->order_no][] = $v->ceping_type;
        }
        foreach ($cepings_arr as $v) {
            if (in_array(2, $v)) {
                $cepings += 1;
            } else {
                $sales += 1;
            }
        }

        //查询给定task_id,operator_id的记录进行更新数量
        $taskApplyNumInfo = (object)$this->getOne(array('task_id' => $task_id, 'operator_id' => $operator_id));
        $taskApplyNumInfo->finish_sale_num = $sales;
        $taskApplyNumInfo->finish_comment_num = $cepings;
        $taskApplyNumInfo->update_time = time();
        $result = $this->update($taskApplyNumInfo);
        return $result;
    }

    public function updateCepingRecordsCount($task_id, $operator_id)
    {
        $this->db->select('id,ceping_type');
        $this->db->from('task_records');
        $this->db->where(array('task_id' => $task_id, 'operator_id' => $operator_id));
        $list = $this->db->get()->result();
        $sales = 0;
        $cepings = 0;
        foreach ($list as $v) {
            if ($v->ceping_type == 1) {
                $sales += 1;
            } else if ($v->ceping_type == 2) {
                $cepings += 1;
            }
        }
        //查询给定task_id,operator_id的记录进行更新数量
        $taskApplyNumInfo = (object)$this->getOne(array('task_id' => $task_id, 'operator_id' => $operator_id));
        $taskApplyNumInfo->finish_sale_num = $sales;
        $taskApplyNumInfo->finish_comment_num = $cepings;
        $taskApplyNumInfo->update_time = time();
        $result = $this->update($taskApplyNumInfo);
        return $result;
    }

    public function descApplyFinishNumber($task_id, $ceping_type, $operator_id)
    {
        $taskApplyNumInfo = (object)$this->getOne(array('task_id' => $task_id, 'operator_id' => $operator_id));
        if ($ceping_type == 1) {
            $taskApplyNumInfo->finish_sale_num = $taskApplyNumInfo->finish_sale_num - 1;
        } elseif ($ceping_type == 2) {
            $taskApplyNumInfo->finish_comment_num = $taskApplyNumInfo->finish_comment_num - 1;
        }

        $taskApplyNumInfo->update_time = time();
        $result = $this->update($taskApplyNumInfo);
        return $result;
    }

    public function getById($id)
    {
        $query = $this->db->where('id', $id)->get($this->table);
        return $query->row();
    }
}
